# This is a sample Python script.
# -*- coding: UTF-8 -*-\
import logging
from datetime import date, datetime

from xToolkit.xstring import xstring

import toolkit
from pyxirr import xirr

from data_alchemy.account_voucher_alchemy import AccountVoucherAlchemy
from data_alchemy.annual_yield_alchemy import AnnualYieldAlchemy
from data_alchemy.investment_flow_alchemy import InvestmentFlowAlchemy
from initLogger import logger
from initXirrPage import FLOW_TYPE_DING_TOU, FLOW_TYPE_TI_XIAN


def xirrTest():
    dates = [date(2022, 1, 1), date(2022, 12, 31)]
    amounts = [-1000, 1200]
    result = xirr(dates, amounts)
    print(result)

    dates = [date(2021, 1, 1), date(2021, 12, 31), date(2022, 12, 31)]
    amounts = [-1000, 0,1200]
    result = xirr(dates, amounts)
    print(result)

    dates = [date(2022, 1, 1), date(2022, 12, 31)]
    amounts = [1000, 1200]
    result = xirr(dates, amounts)
    print(result)



def batchProcessInvestmentPutIntoData():
    '''
    函数功能：对investment data 进行批量处理
    :return:
    '''
    accountVoucherAlchemy = AccountVoucherAlchemy()
    investmentVoucherInfor =  accountVoucherAlchemy.SearchVoucherBySubject("property_increase_name","资产->投资->理财%")
    print(investmentVoucherInfor)

    for investmentVoucherItem in  investmentVoucherInfor:
        if investmentVoucherItem.property_increase_value == investmentVoucherItem.property_decrease_value:
            #资产增减相同，为实际资金投入；去除掉随出归做“历年积累”的资金，这部分资金后续单独计算。

            subStringList = investmentVoucherItem.property_increase_name.split("->")
            substringListLen = len(subStringList)
            investmentName = subStringList[substringListLen-1]
            investmentFlowAlchemy = InvestmentFlowAlchemy(investmentDate = investmentVoucherItem.account_date,
                                                      investmentValue = investmentVoucherItem.property_increase_value,
                                                      investmentPath = investmentVoucherItem.property_increase_name,
                                                      flowType = FLOW_TYPE_DING_TOU,
                                                      voucherId = investmentVoucherItem.id)
            investmentFlowAlchemy.AddInvestmentItem()


def batchProcessInvestmentFetchData():
    '''
    函数功能：批量处理投资金额取出的数据
    :return:
    '''
    accountVoucherAlchemy = AccountVoucherAlchemy()
    investmentVoucherInfor =  accountVoucherAlchemy.SearchVoucherBySubject("property_decrease_name","资产->投资->理财%")
    print(investmentVoucherInfor)

    for investmentVoucherItem in  investmentVoucherInfor:
        if investmentVoucherItem.property_increase_value == investmentVoucherItem.property_decrease_value:
            #资产增减相同，为实际资金投入；去除掉随出归做“历年积累”的资金，这部分资金后续单独计算。

            subStringList = investmentVoucherItem.property_decrease_name.split("->")
            substringListLen = len(subStringList)
            investmentName = subStringList[substringListLen - 1]
            investmentFlowAlchemy = InvestmentFlowAlchemy(investmentDate = investmentVoucherItem.account_date,
                                                      investmentValue = investmentVoucherItem.property_decrease_value*(-1),
                                                      investmentPath = investmentVoucherItem.property_decrease_name,
                                                      flowType = FLOW_TYPE_TI_XIAN,
                                                      voucherId = investmentVoucherItem.id)
            investmentFlowAlchemy.AddInvestmentItem()


def batchProcessInvestmentData():
    '''
    函数功能：对历史投资数据进行批处理
    :return:
    '''
    #处理投资投入
    batchProcessInvestmentPutIntoData()
    #处理投资支出
    batchProcessInvestmentFetchData()


def generateProductAnnualYield(investmentName, finalDate, finalValue):
    '''
    函数功能：生成一条年化收益率的分析记录
    :return:
    '''
    #currentDate = datetime.now()  # 记录当前事件
    #investmentName = "沪深300指数基金"
    #finalDate = date(2023, 8, 13)   #最终的计算时间
    #finalValue = 21616.73    #最终的金额数


    #######################################################
    # 分红的金额暂时还不涉及，后续补充这部分功能
    #######################################################
    dividendTotalValue = 0.0

    xirrResult, savedTotalMoneyValue, drawedTotalMoneyValue = computeXirrForInvestmentItem(investmentName, finalDate, finalValue)
    annualYieldAlchemy = AnnualYieldAlchemy( observeDate=finalDate,
                                             investmentName=investmentName,
                                             savedTotalMoneyValue=savedTotalMoneyValue,
                                             drawedTotalMoneyValue=drawedTotalMoneyValue,
                                             dividendTotalValue=dividendTotalValue,
                                             currentRealTotalValue=finalValue,
                                             xirrValue=xirrResult)
    annualYieldAlchemy.AddInvestmentItem()


def computeXirrForInvestmentItem(investmentName, finalDate, finalValue):
    '''
    函数功能：计算指定投资的现金流收益率
    :param investmentName:  投资产品的路径
    :param finalDate:  最终的产品计算时间点节点
    :param finalValue: 最终的产品在该时间节点的金额
    :return:
    '''

    investmentFlowAlchemy = InvestmentFlowAlchemy()
    investmentFlowResult =  investmentFlowAlchemy.SearchInvestmentFlowByName(investmentName)
    dateList = []
    amountList = []
    savedTotalMoneyValue = 0.0
    drawedTotalMoneyValue = 0.0


    for investFlowItem in investmentFlowResult:
        dateList.append(investFlowItem.investment_date)
        amountList.append(investFlowItem.investment_value)
        if investFlowItem.investment_value>0:
            #计算累计存入金额
            savedTotalMoneyValue = savedTotalMoneyValue + investFlowItem.investment_value
        elif investFlowItem.investment_value<0:
            drawedTotalMoneyValue = drawedTotalMoneyValue + investFlowItem.investment_value*(-1)



    dateList.append(finalDate)
    amountList.append(finalValue*(-1))


    xirrResult = xirr(dateList, amountList)

    return xirrResult, savedTotalMoneyValue, drawedTotalMoneyValue

def generateAllProductIndicator():
    '''
    函数功能：计算所有投资产品的各项指标
    :return:
    '''

    investmentFlowAlchemy = InvestmentFlowAlchemy()
    investmentNameList = investmentFlowAlchemy.GetInvestmentNameList()

    for  investmentNameItem in  investmentNameList:
        generateProductAnnualYield(investmentNameItem, date(2023, 8, 13), 21616.73)

def main():

    #generateAllProductIndicator()
    logger.debug("############################")
    generateProductAnnualYield(investmentName = "资产->投资->理财->招商产业债券A基金",
                               finalDate = date(2023, 8, 13),
                               finalValue = 21616.73)

    logger.debug("############################")
    generateProductAnnualYield(investmentName="中证500指数增强基金",
                               finalDate=date(2023, 8, 13),
                               finalValue=18799.27)

    logger.debug("############################")
    generateProductAnnualYield(investmentName="沪深300指数基金",
                               finalDate=date(2023, 8, 13),
                               finalValue=27896.06)

    logger.debug("############################")
    generateProductAnnualYield(investmentName="鹏华丰禄债券基金",
                               finalDate=date(2023, 8, 13),
                               finalValue=14561.09)
    logger.debug("############################")

    '''
    #计算报错，还有一部分历史积累没有算
    generateProductAnnualYield(investmentName="招行货币基金",
                               finalDate=date(2023, 8, 13),
                               finalValue=282124.00)
    '''



    #xirrTest()
    #computeXirrForInvestmentItem("资产->投资->理财->招商产业债券A基金")
    #batchProcessInvestmentData()
    #xirrTest()
    pass


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    #print_hi('PyCharm')
    main()


# See PyCharm help at https://www.jetbrains.com/help/pycharm/
